package com.peek.controller;

import com.peek.util.HelpMe;
import com.peek.util.Zip;
import com.xiaoleilu.hutool.io.FileUtil;
import com.xiaoleilu.hutool.io.IoUtil;
import com.xiaoleilu.hutool.io.StreamProgress;
import com.xiaoleilu.hutool.system.OsInfo;
import com.xiaoleilu.hutool.system.SystemUtil;
import com.xiaoleilu.hutool.util.ZipUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.embedded.MimeMappings;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * Created by mengdexuan on 2017/8/27 12:28.
 */
@Controller
@RequestMapping("/file")
public class FileUploadController {

	private static Logger log = LoggerFactory.getLogger(FileUploadController.class);
	private static OsInfo osInfo = SystemUtil.getOsInfo();


	@RequestMapping(value = "/upload")
	@ResponseBody
	public String batchUpload(HttpServletRequest request, String currDir) throws IOException {
		if (HelpMe.isNull(currDir)) {
			log.info("当前目录为空，上传失败！");
			return "当前目录为空，上传失败！";
		}
		log.info("当前目录 --> " + currDir);
		List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
		MultipartFile file = null;
		BufferedOutputStream stream = null;
		for (int i = 0; i < files.size(); ++i) {
			file = files.get(i);
			if (!file.isEmpty()) {
				String extName = FileUtil.extName(file.getOriginalFilename());
				String path = currDir + osInfo.getFileSeparator() + file.getOriginalFilename();
				log.info("上传文件 --> " + path);
				try {
					byte[] bytes = file.getBytes();
					stream = new BufferedOutputStream(new FileOutputStream(new File(path)));
					stream.write(bytes);
					stream.close();
				} catch (Exception e) {
					stream = null;
					return "You failed to upload " + i + " => " + e.getMessage();
				}

				if ("zip".equals(extName)) {//上传的是压缩包，只对 zip 进行判断
					Zip.unZip(path);//解压，并保存原压缩文件
				}

			} else {
				return "You failed to upload " + i + " because the file was empty.";
			}
		}
		return "upload successful";
	}




	private static MimeMappings MIME_MAP = new MimeMappings(MimeMappings.DEFAULT);

	@RequestMapping(value = "/download")
	public void download(HttpServletResponse response, String dirId) throws Exception{
		try {
			dirId = java.net.URLDecoder.decode(dirId, "UTF-8");
			log.info("下载文件 --> " + dirId);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		File file = new File(dirId);
		if (file.isDirectory()) {//如果是目录，压缩后再下载
			file = ZipUtil.zip(file);
		}
		String filename = file.getName();
		try {
			filename = java.net.URLEncoder.encode(filename, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}


		response.setHeader("Content-Disposition", "attachment;filename=" + filename);
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/x-msdownload;charset=UTF-8");
		ServletOutputStream out = response.getOutputStream();

		FileInputStream in = new FileInputStream(file);
		IoUtil.copyByNIO(in, out, 1024, (StreamProgress) null);
		IoUtil.close(in);
		IoUtil.close(out);
	}


	@RequestMapping(value = "/view")
	public String view(String dirId, Model model) {
		model.addAttribute("dirId",dirId);
		long time1 = System.currentTimeMillis();
		try {
			dirId = java.net.URLDecoder.decode(dirId, "UTF-8");
			log.info("查看文件 --> " + dirId);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		File file = new File(dirId);
		long size = FileUtil.size(file);

		long flag = 1024 * 1024 * 50;//50M
		String content = "";
		if (size>flag){
			content = "文件大于 50M ，请下载后查看！";
		}else {
			content = FileUtil.readString(file,"utf-8");
		}

		model.addAttribute("content",content);
		long time2 = System.currentTimeMillis();

		log.info("查看耗时 --> "+(time2-time1) +"(ms)");

		return "view";
	}



	@RequestMapping(value = "/content")
	@ResponseBody
	public String saveContent(String dirId, String content) {
		try {
			dirId = java.net.URLDecoder.decode(dirId, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}


		FileUtil.writeString(content,dirId,"utf-8");

		return "ok";
	}














	private static String getMimeByFileName(String fileName) {
		String mime = MIME_MAP.get(FileUtil.extName(fileName));
		if (HelpMe.isNull(mime)) {
			mime = MediaType.APPLICATION_OCTET_STREAM_VALUE;
		}
		return mime;
	}














}





















